package com.ft.oa.service.dev.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.dev.DevProblem;
import com.ft.oa.domain.dev.DevProblemItem;
import com.ft.oa.domain.dev.DevTaskItem;
import com.ft.oa.domain.dto.ApiResult;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.mapper.dev.DevProblemItemMapper;
import com.ft.oa.mapper.dev.DevProblemMapper;
import com.ft.oa.service.dev.DevProblemItemService;
import com.ft.oa.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: yihui
 * Date: 2022/1/20 14:15 PM
 * FileName: DevProblemItemServiceImpl
 * Description: 研发问题进展
 */
@Transactional
@Service
public class DevProblemItemServiceImpl implements DevProblemItemService {

    @Resource
    DevProblemItemMapper devProblemItemMapper;

    @Resource
    DevProblemMapper devProblemMapper;

    @Override
    public ApiResult add(DevProblemItem devProblemItem) {
        DevProblem devProblem = devProblemMapper.selectById(devProblemItem.getDevProblemId());
        Map queryMap = new HashMap();
        queryMap.put("dev_problem_id",devProblemItem.getDevProblemId());
        List<DevTaskItem> devTaskItemList = devProblemItemMapper.selectByMap(queryMap);
        if (devTaskItemList.size() == 0){
            devProblem.setActualStartDate(LocalDate.now());
        }
        if(100 == devProblemItem.getProgressRate()){
            devProblem.setProblemStatus(2);
            devProblem.setActualFinishDate(LocalDate.now());
        }else{
            devProblem.setProblemStatus(1);
        }
        devProblem.setProgressRate(devProblemItem.getProgressRate());
        devProblemMapper.updateById(devProblem);
        //根据当前进展更新任务进度
        devProblemItem.setCreateDate(LocalDateTime.now());
        Long createStaffId = SecurityUtils.getCurrentUser().getId();
        devProblemItem.setCreateStaffId(createStaffId);
        devProblemItemMapper.insert(devProblemItem);
        return ApiResult.simpleSuccess();
    }

    @Override
    public Page<DevProblemItem> page(DevProblemItem devProblemItem) {
        Page<DevProblemItem> pages = new Page<>(devProblemItem.getPage(), devProblemItem.getSize());
        QueryWrapper<DevProblemItem> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager()), DevProblemItem::getCreateStaffId,SecurityUtils.getCurrentUser().getId())
                .eq(DevProblemItem::getDevProblemId, devProblemItem.getDevProblemId());
        Page<DevProblemItem> result = devProblemItemMapper.selectPage(pages, wrapper);
        return result;
    }
}
